﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarInfoDBAccess.Model;
using CarStoreDB.ADODotNet;
using System.Configuration;
using System.Drawing;
using System.IO;


namespace CarInfoSpider
{
    public class DBAccess
    {
        private static DBAccess dba;

        public static DBAccess Instance
        {
            get
            {
                if (dba == null)
                    dba = new DBAccess();
                return dba;
            }
        }


        public void Save2DB(List<CarInfoDBAccess.DBAccess_New.CSBrand> brands)
        {
            if (brands != null)
            {
                string cs = "";
                foreach (var item in ConfigurationManager.ConnectionStrings)
                {
                    System.Diagnostics.Debug.WriteLine(item.ToString());
                    cs = item.ToString();
                }
                //string cs = @"metadata=res://*/ADODotNet.Model1.csdl|res://*/ADODotNet.Model1.ssdl|res://*/ADODotNet.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=WS-EVANSL-01\\MSSQL2008;Initial Catalog=MvcCarDB;Integrated Security=True;MultipleActiveResultSets=True&quot;" + " providerName=\"System.Data.EntityClient";
                using (var db = new CarStoreDB.ADODotNet.Entities())
                {
                    foreach (var brand in brands)
                    {


                        foreach (var ct in brand.CSCarType)
                        {
                            CarStoreDB.ADODotNet.Type t = new CarStoreDB.ADODotNet.Type();
                            t.TypeName = ct.Name;
                            t.Description = ct.Url;
                            foreach (var ci in ct.CSCarInfo)
                            {
                                CarStoreDB.ADODotNet.Car car = new Car();
                                car.CarName = ci.Name;
                                car.Description = ci.Type;
                                car.Price = Convert.ToDecimal(ci.Price);
                                // car.Image = ci.Image;
                                car.Count = 10;
                                t.Car.Add(car);
                            }
                            db.AddToType(t);

                        }

                    }

                    db.SaveChanges();
                }
            }
        }

        public void Save2DB(CarInfoDBAccess.DBAccess_New.CSBrand brand)
        {
            if (brand != null)
            {
                using (var db = new CarStoreDB.ADODotNet.Entities())
                {
                    var dbBrand = db.Brand.FirstOrDefault(b => b.BrandName == brand.Name);
                    if (dbBrand == null)
                    {
                        CarStoreDB.ADODotNet.Brand b = new CarStoreDB.ADODotNet.Brand();
                        b.BrandName = brand.Name;
                        b.Description = brand.Url;

                        db.AddToBrand(b);
                        db.SaveChanges();

                    }


                    var dbBrand4type = db.Brand.First(b => b.BrandName == brand.Name);
                    foreach (var ct in brand.CSCarType)
                    {
                        foreach (var ci in ct.CSCarInfo)
                        {
                            var dbType = db.Type.FirstOrDefault(t => t.TypeName == ci.Typename);
                            if (dbType == null)
                            {
                                CarStoreDB.ADODotNet.Type type = new CarStoreDB.ADODotNet.Type();
                                type.TypeName = ci.Typename;

                                db.AddToType(type);
                                db.SaveChanges();
                            }
                        }
                    }

                    foreach (var ct in brand.CSCarType)
                    {
                        foreach (var ci in ct.CSCarInfo)
                        {
                            var dbCar = db.Car.FirstOrDefault(c => c.CarName == ci.Name);
                            if (dbCar == null)
                            {
                                CarStoreDB.ADODotNet.Car car = new Car();
                                car.CarName = ci.Name;
                                car.Count = 10;
                                car.Price = Convert.ToDecimal(ci.Price);
                                car.Brand = dbBrand4type;

                                var dbType = db.Type.FirstOrDefault(t => t.TypeName == ci.Typename);
                                car.Type = dbType;

                                db.AddToCar(car);
                                db.SaveChanges();
                                SavePic2HDD(ci.Img, car.CarId);
                                car.ImagePath = string.Format("\\CarPic\\{0}\\", car.CarId);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }

        }

        private void SaveType2DB(CarStoreDB.ADODotNet.Type type)
        {
            using (var db = new CarStoreDB.ADODotNet.Entities())
            {
                db.AddToType(type);
                db.SaveChanges();
            }
        }

        private void SaveCar2DB(CarInfoDBAccess.DBAccess_New.CSBrand ci)
        {
            using (var db = new CarStoreDB.ADODotNet.Entities())
            {

            }
        }

        private void SavePic2HDD(Image img, int id)
        {
            if (img == null)
                return;
            string FilePath = string.Format("{1}\\CarPic\\{0}\\", id, System.Environment.CurrentDirectory);
            // string FilePath = string.Format("\\CarPic\\{0}\\index.jpg", id);
            // string FilePath = string.Format("{0}.jpg", id);
            //Bitmap bm = new Bitmap(img.Width, img.Height);
            //Graphics g = Graphics.FromImage(bm);
            //g.DrawImage(img, 0, 0);
            //g.DrawLine(Pens.Black, 0, 0, 1, 1);
            //bm.Save(FilePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //g.Dispose();

            img = KiResizeImage(img, 220, 150);
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            FilePath += "index.jpg";
            try
            {
                using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate))
                {
                    img.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            catch (Exception ex)
            { System.Diagnostics.Debug.WriteLine(ex.Message); }
        }

        /// <summary>
        /// Resize图片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的宽度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留着，暂时未用</param>
        /// <returns>处理以后的图片</returns>
        private Image KiResizeImage(Image bmp, int newW, int newH)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                // 插值算法的质量
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }
    }
}
